import React, { useEffect, useState } from 'react';
import { Button, Container, Input, InputGroup } from 'rsuite';
import SearchIcon from '@rsuite/icons/Search';
import Api, { ModelProps } from '../src/Api';
import { ModelClassifer } from './ModelClassifier';

var viewer: ModelClassifer;

function animate(dt: number) {
  requestAnimationFrame(animate);
}


export default function Classifier() {
  const [inited] = useState<Array<number>>([]);
  const [keyword, setKeyword] = useState('');
  let canvasRef = React.createRef<HTMLCanvasElement>();

  useEffect(() => {
    if (canvasRef.current instanceof HTMLCanvasElement) {
      let canvas = canvasRef.current;
      if (inited.length == 0) {
        inited.push(Date.now());
        viewer = new ModelClassifer(canvas);
        animate(0);
      } else {
        if (viewer) {
          viewer.resize();
        }
      }
    }
  }, []);


  const search = async () => {
    if (viewer) {
      const rows = await Api.search(keyword, 0, 10)
      for (let row of rows) {
        if (!row.tags) {
          let tags = await viewer.add(row.url)
          row.tags = tags.join(";");
          await Api.put(row);
        }
      }
    }
  }


  const run = async () => {
    if (viewer) {
      let from = 0;
      let rows = new Array<ModelProps>();
      do {
        rows = await Api.search(keyword, from, 10)
        for (let row of rows) {
          if (!row.tags) {
            try {
              let tags = await viewer.add(row.url)
              row.tags = tags.join(" ");
              row.url = '';
              await Api.put(row);
            } catch (error) {

            }
          }
        }
        from += 10;
      } while (rows.length == 10)
    }
  }

  return (
    <Container>
      <canvas ref={canvasRef}></canvas>
      <InputGroup style={{ position: 'absolute', bottom: 40, left: "8%", width: '84%' }}>
        <Button onClick={run} >Run</Button>
        <Input onPressEnter={search} onChange={(v) => { setKeyword(v); }}></Input>
        <InputGroup.Button>
          <SearchIcon onClick={search} />
        </InputGroup.Button>
      </InputGroup>
    </Container>
  )
}

